package org.example.utils;


import org.example.config.PropertiesConfig;
import org.example.domain.User;
import org.example.service.UserService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


/**
 * 自定义加密方式
 */
public class MD5Util implements PasswordEncoder {
    // 盐值
    private static String salt = PropertiesConfig.getSalt();

    /**
     * 加密
     * 加密两次,第二次加密放上盐值
     * @param charSequence 字符串
     * @return
     */
    @Override
    public String encode(CharSequence charSequence) {
        String data = DigestUtils.md5DigestAsHex(charSequence.toString().getBytes());
        return DigestUtils.md5DigestAsHex((data+salt).getBytes());
    }

    public static String encode(String charSequence){
        String data = DigestUtils.md5DigestAsHex(charSequence.toString().getBytes());
        return DigestUtils.md5DigestAsHex((data+salt).getBytes());
    }
    public static String encode(String charSequence,String salt){
        String data = DigestUtils.md5DigestAsHex(charSequence.toString().getBytes());
        return DigestUtils.md5DigestAsHex((data+salt).getBytes());
    }

    /**
     * 匹配是否相等
     * @param charSequence 未加密的字符串
     * @param s 已加密的字符串
     * @return
     */
    @Override
    public boolean matches(CharSequence charSequence, String s) {
        if (!StringUtils.hasText(charSequence)) return false;
        String data = encode(charSequence);
        return data.equals(s);
    }
    public static boolean matches(String charSequence,String salt, String encrypt) {
        if (!StringUtils.hasText(charSequence)) return false;
        String data = DigestUtils.md5DigestAsHex(charSequence.getBytes());
        data = DigestUtils.md5DigestAsHex((data+salt).getBytes());
        return data.equals(encrypt);
    }

}